package cn.xkai.exercise.b;

import com.google.gson.Gson;

import java.util.Objects;

/**
 * @description: 奇偶链表
 * @author: kaixiang
 * @date: 2022-07-25
 **/
public class Solution92 {
    public ListNode oddEvenList(ListNode head) {
        //如果链表小于3个那么直接返回
        if (head == null || head.next == null || head.next.next == null) {
            return head;
        }
        //定义第一条指针
        ListNode secondhead = head;
        //定义第二条指针
        ListNode oneHead = head.next;
        //定义第一条指针的开始位置
        ListNode one = secondhead;
        //定义第二条指针开始的位置
        ListNode two = oneHead;
        while (secondhead != null && secondhead.next != null && secondhead.next.next != null) {
            //然后这里就是相互的删除中间的元素，也就是逻辑删除
            secondhead.next = secondhead.next.next;
            secondhead = secondhead.next;
            oneHead.next = oneHead.next.next;
            oneHead = oneHead.next;
        }
        secondhead.next = two;
        return one;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof ListNode)) return false;
            ListNode listNode = (ListNode) o;
            return val == listNode.val && Objects.equals(next, listNode.next);
        }

        @Override
        public int hashCode() {
            return Objects.hash(val, next);
        }
    }

    public static void main(String[] args) {
        ListNode node5 = new ListNode(5);
        ListNode node4 = new ListNode(4);
        ListNode node3 = new ListNode(3);
        ListNode node2 = new ListNode(2);
        ListNode node1 = new ListNode(1);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        Solution92 solution92 = new Solution92();
        System.out.println(new Gson().toJson(solution92.oddEvenList(node1)));
    }
}
